" ---------! GENERAL SETTINGS !----------

" Syntax highlight
syntax on

set nocompatible
set history=500
set keymap=russian-jcukenwin
set iminsert=0
set imsearch=0
set clipboard=unnamedplus
set encoding=UTF-8
set completeopt=menuone,noinsert
set filetype
set enc=utf-8 " always utf-8
set novisualbell
set nu " lines numbering


set showcmd
set tildeop
set autoread
" Enable filetype plugins
filetype plugin on
filetype indent on
" Set to auto read when a file is changed from the outside
set autoread
au FocusGained,BufEnter * checktime

" '\' and ',' are leadres for vim from now
let mapleader = ","

" Some useful remappings
nmap <leader>w :w!<Cr>
nmap <leader>te :tabe 
nmap <leader>tc :tabc<Cr>
nmap <leader>q :q<Cr>
nmap <leader>a :qa!<Cr>

" Make Vim always render the sign column (except nerdtree):
set signcolumn=yes
autocmd FileType nerdtree setlocal signcolumn=no

" Set 7 lines up/down of cursor - when moving vertically using j/k
set so=7

" Turn on the Wild menu
set wildmenu

" Ignore compiled files
set wildignore=*.o,*~,*.pyc
if has("win16") || has("win32")
    set wildignore+=.git\*,.hg\*,.svn\*
else
    set wildignore+=*/.git/*,*/.hg/*,*/.svn/*,*/.DS_Store
endif

" Always show current positon
set ruler

" A buffer becomes hidden when it is abandoned
set hid

" Ignore case when searching
set ignorecase

" When searching try to be smart about cases
set smartcase

" Makes search act like search in modern browsers
set incsearch

" Don't redraw while executing macros (good performance config)
set lazyredraw

" For regular expressions turn magic on
set magic

" Show matching brackets when text indicator is over them
set showmatch

" How many tenths of a second to blink when matching brackets
set mat=2

" No annoying sound on errors
set noerrorbells
set novisualbell
set t_vb=
set tm=500

" Set regular expression engine automatically
set regexpengine=0

" Set extra options when running in GUI mode
if has("gui_running")
    set guioptions-=T
    set guioptions-=e
    set t_Co=256
    set guitablabel=%M\ %t
endif

" Set utf8 as standard encoding and en_US as the standard language
set encoding=utf8

" Use Unix as the standard file type
set ffs=unix,dos,mac

" Turn backup off, since most stuff is in SVN, git etc. anyway...
set nobackup
set nowb
set noswapfile

" Wrap to next line after reaching last char in line
set whichwrap+=h,l

" Use spaces instead of tabs
set expandtab

" Be smart when using tabs ;)
set smarttab

" 1 tab == 4 spaces
set shiftwidth=4
set tabstop=4

" Linebreak on 500 characters
set lbr
set tw=500

set ai "Auto indent
set si "Smart indent
set wrap "Wrap lines

" Visual mode pressing * or # searches for the current selection. Super useful! 
vnoremap <silent> * :<C-u>call VisualSelection('', '')<CR>/<C-R>=@/<CR><CR>
vnoremap <silent> # :<C-u>call VisualSelection('', '')<CR>?<C-R>=@/<CR><CR>

" Map <Space> to / (search) and Ctrl-<Space> to ? (backwards search)
map <space> /
map <C-space> ?

" Disable highlight when <leader><cr> is pressed
map <silent> <leader><space> :set hls!<cr>

" Installing VimPlug and Neovim automaticly
"
" ***************! PLUGINS !*******************
"TODO: Check if WHAT? 
call plug#begin(has('nvim') ? '~/.vim/plugged' : '~/.vim/plugged')
" call plug#begin('~/.vim/plugged')
" ---------===         Specific        ===-------------

Plug 'lambdalisue/suda.vim'
Plug 'radenling/vim-dispatch-neovim'
Plug 'nvim-lua/plenary.nvim'

" ---------=== Navigation ===-------------

Plug 'scrooloose/nerdtree'
Plug 'nvim-telescope/telescope.nvim', { 'tag': '0.1.4' }

" ---------=== Visualisation ===-------------

Plug 'bling/vim-airline'
Plug 'vim-airline/vim-airline-themes'
Plug 'jonathanfilip/vim-lucius'
Plug 'cocopon/iceberg.vim'
" Plug 'jonstoler/werewolf.vim' "TODO made by yourself time change

"---------=== Writing Help ===-------------

" Plug 'ervandew/supertab' TODO
Plug 'anyakichi/vim-surround'

"---------=== Developing ===-------------

Plug 'nvim-treesitter/nvim-treesitter', {'do': ':TSUpdate'}
Plug 'sheerun/vim-polyglot'
Plug 'jpalardy/vim-slime' ,{ 'for': ['lisp'] }
Plug 'tpope/vim-commentary'
Plug 'valloric/youcompleteme', { 'for': ['cpp','python', 'html', 'c', 'go'], 'do': './install.py' }
" Plug 'l3nkz/ycmconf' TODO
Plug 'iamcco/markdown-preview.nvim', { 'do': { -> mkdp#util#install() }, 'for': ['markdown', 'vim-plug']}

" --- Clojure ---

Plug 'clojure-vim/vim-jack-in', {'for': ['clojure']}
" Plug 'Olical/conjure', {'for': ['clojure']}

" --- Python ---

Plug 'python-mode/python-mode', { 'for': ['python'] }

" --- JavaScript ---

Plug 'pangloss/vim-javascript', { 'for': 'js'}

" --- WEB ---

Plug 'mattn/emmet-vim',  { 'for': 'html'}

" --- Nim ---
" Plug 'zah/nim.vim' 

call plug#end()


" ---------! PLUGINS SETTINGS !----------
" ------ TELESCOPE  ------
nnoremap <leader>ff <cmd>Telescope find_files<cr>
nnoremap <leader>fg <cmd>Telescope live_grep<cr>
nnoremap <leader>fb <cmd>Telescope buffers<cr>
nnoremap <leader>fh <cmd>Telescope help_tags<cr>

nnoremap <leader>fc <cmd>lua require('telescope.builtin').treesitter()<cr>

" --- MARKDOWN PREVIEW --- 

" --- NIM.VIM --- 
fun! JumpToDef()
  if exists("*GotoDefinition_" . &filetype)
    call GotoDefinition_{&filetype}()
  else
    exe "norm! \<C-]>"
  endif
endf

" Jump to tag
nn <M-g> :call JumpToDef()<cr>
ino <M-g> <esc>:call JumpToDef()<cr>i


" --- SLIME ---
let g:slime_target = "tmux"
let g:slime_default_config = {"socket_name": get(split($TMUX, ","), 0), "target_pane": "{last}"}
let g:slime_no_mappings = 1

xmap <leader>s <Plug>SlimeRegionSend
" nmap <leader>s <Plug>SlimeMotionSend
nmap <leader>ss <Plug>SlimeLineSend

" --- NERD-TREE --- 
" *** Visuality *** 
let NERDTreeMinimalUI = 1
let NERDTreeDirArrows = 1

let NERDTreeMouseMode = 2

let g:NERDTreeDirArrowExpandable =  '▸'
let g:NERDTreeDirArrowCollapsible =  '▾'

" *** functional ***

let NERDTreeAutoDeleteBuffer = 1
" Key to open:
nnoremap <C-n> :NERDTree<CR>

let NERDTreeIgnore=['\~$', '\.pyc$', '\.pyo$', '\pycache__$', 'pip-log\.txt$', '\.o$', '\.__pyc$', '\.swp$', '\.swo$']

" vim with no args openning nerdtree
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif


" --- VIM-AIRLINE --- 
" *** Change color scheme *** 
colorscheme iceberg
" LuciusBlackLowContrast
" LuciusDark

" *** Settings *** 
set laststatus=2
let g:airline_theme='lucius'
let g:airline_inactive_alt_sep=1
let g:airline_powerline_fonts = 1
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#searchcount#enabled = 1
let g:airline#extensions#tabline#formatter = 'unique_tail'
let g:airline#extensions#nerdtree_statusline = 1

" need to install plugin tmuxline
" let g:airline_extensions = ['tabline', 'tmuxline']
let g:airline_extensions = ['tabline']


"" --- warewolf ---
" changing colorscheme based on time of day
" let g:werewolf_day_themes = ['LuciusDark']
" let g:werewolf_night_themes = ['LuciusBlackLowContrast']
" default 8, use 24 hour format
" let g:werewolf_day_start = 8
" default 20, 24 hour format
" let g:werewolf_day_end = 20


" --- FILTETYPES --- 
" *** Docker *** 
augroup filetypedetect
    au! BufRead,BufNewFile DockerFile setfiletype dockerfile
augroup END
" COMMENTS FOR IT
autocmd FileType dockerfile setlocal commentstring=#%s


" fdoc is yaml
autocmd BufRead,BufNewFile *.fdoc set filetype=yaml
" md is markdown
autocmd BufRead,BufNewFile *.md set filetype=markdown
autocmd FileType markdown setlocal signcolumn=no
autocmd BufRead,BufNewFile *.md set spell


" --- PYTHON SETTINGS --- 
let g:python3_host_prog='/usr/bin/python3'
let g:python_host_prog='/usr/bin/python'

" *** PYMODE *** 
let g:pymode = 1
let g:pymode_python = 'python3'

" support virtualenv
let g:pymode_virtualenv = 1

let g:pymode_trim_whitespaces = 1

let g:pymode_options_max_line_length = 79
let g:pymode_options_colorcolumn = 1
let g:pymode_options = 1

let g:pymode_folding = 0 

let g:pymode_breakpoint = 1
let g:pymode_breakpoint_bind = '<leader>b'

let g:pymode_lint = 1
let g:pymode_lint_checkers = [ 'pyflakes', 'pep8']

let g:pymode_lint_ignore = ['C0114', 'E501']
let g:pymode_lint_on_write = 1 
let g:pymode_lint_message = 1
let g:pymode_lint_cwindow = 0

let g:pymode_motion = 1

let g:pymode_syntax = 1
let g:pymode_syntax_all = 1
let g:pymode_syntax_indent_errors = g:pymode_syntax_all
let g:pymode_syntax_space_errors = g:pymode_syntax_all

" отключить autofold по коду
let g:pymode_folding = 0

let g:pymode_doc = 1
let g:pymode_doc_bind = 'K'

augroup python
    autocmd FileType c map <F7> :YcmCompleter Format<Cr>
augroup end

augroup python
    autocmd!
    autocmd FileType python setlocal ts=4 sts=4 sw=4
    autocmd FileType python set textwidth=79
    autocmd FileType python set autoindent 
    autocmd FileType python map <leader><F7> :PymodeLint<Cr>
    autocmd FileType python nnoremap <F7> :PymodeLintAuto<Cr>
    autocmd FileType python syntax keyword pythonBreakpoint breakpoint display
    autocmd FileType python highlight def link pythonBreakpoint Error
augroup end
" syn keyword pythonBreakpoint 'breakpoint()'
" highlight def link pythonBreakpoint Error



iab utf! # -*- coding: utf-8 -*-
iab main! if __name__ == '__main__':<Cr>
iab init! def __init__(self
iab sh! #!/bin/sh<Cr>

" --- JS SETTINGS ---
let g:javascript_plugin_jsdoc = 1


" EMMET SETTINGS
" TODO : Change
let g:user_emmet_leader_key='\'

" --- YOUCOMPLETE SETTINGS --- 
let g:ycm_log_level = 'info'
" TODO
let g:ycm_global_ycm_extra_conf = '/home/katok/.vim/plugged/youcompleteme/.ycm_extra_conf.py' 

let g:ycm_min_num_of_chars_for_completion = 1
let g:ycm_max_num_candidates_to_detail = 3

let g:ycm_filetype_blacklist = {
      \ 'tagbar': 1,
      \ 'notes': 1,
      \ 'markdown': 1,
      \ 'netrw': 1,
      \ 'unite': 1,
      \ 'text': 1,
      \ 'vimwiki': 1,
      \ 'pandoc': 1,
      \ 'infolog': 1,
      \ 'leaderf': 1,
      \ 'mail': 1
      \}

let g:ycm_filepath_blacklist = {
      \ 'html': 1,
      \ 'jsx': 1,
      \ 'xml': 1,
      \}

let g:ycm_semantic_triggers =  {
  \   'c': ['->', '.'],
  \   'cpp,cuda,objcpp': ['->', '.', '::'],
  \   'perl': ['->'],
  \   'php': ['->', '::'],
  \   'cs,d,elixir,go,groovy,java,javascript,julia,perl6,python,scala,typescript,vb': ['.'],
  \   'ruby,rust': ['.', '::'],
  \ }



" Close preview window after completing the insertion
" let g:ycm_autoclose_preview_window_after_insertion = 1
" let g:ycm_autoclose_preview_window_after_completion = 1

" let g:ycm_always_populate_location_list = 1      " Always populae diagnostics list
" let g:ycm_enable_diagnostic_signs = 1            " Enable line highligting diagnostics
" let g:ycm_open_loclist_on_ycm_diags = 1          " Open location list to view diagnostics

" let g:ycm_max_num_candidates = 20                " Max number of completion suggestions 
" let g:ycm_max_num_identifier_candidates = 10     " Max number of identifier-based suggestions
let g:ycm_auto_trigger = 1                       " Enable completion menu
" let g:ycm_show_diagnostic_ui = 1                 " Show diagnostic display features
" let g:ycm_error_symbol = '>>'                    " The error symbol in Vim gutter
" let g:ycm_enable_diagnostic_signs = 1            " Display icons in Vim's gutter, error, warnings
" let g:ycm_enable_diagnostic_highlighting = 1     " Highlight regions of diagnostic text
" let g:ycm_echo_current_diagnostic = 1            " Echo line's diagnostic that cursor is on


" ---------! END OF PLUGINS SETTINGS !----------


" ---------! OTHERS !---------------------------

" For easily switching windows
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l

" For changing size of the windows
" TODO THIS SHIT

" Minus
" nnoremap <leader>_ <C-w>- 
"  Plus
" nnoremap <leader>- <C-w>+



" Remap to leader + cntrl?
map <F7> gg=G<C-o>

" Enable basic mouse behavior such as resizing buffers.
set mouse=a

" Controlling cursor after exit (not to change cursor in terminal)
augroup change_cursor
    au!
    au ExitPre * :set guicursor=a:ver90
    au VimLeave * set guicursor=a:ver90
    "au VimLeave * set guicursor=a:ver10-blinkwait800
augroup END

if exists('$TMUX') 
    if has('nvim')
        set termguicolors
    else
        set term=screen-256color 
    endif
endif


" прячем панельки
" set guioptions-=m   " меню
" set guioptions-=T    " тулбар
" set guioptions-=r   "  скроллбары

" йцукен клава в режиме вставки
highlight lCursor guifg=NONE guibg=Cya

" Руззкий язык ёмаё
setlocal spell spelllang=ru_yo,en_us

" Disable perl provider
let g:loaded_perl_provider = 0

" delete without yanking
nnoremap <leader>d "_d
vnoremap <leader>d "_d

" replace currently selected text with default register
" without yanking it
vnoremap <leader>p "_dP

function! VisualSelection(direction, extra_filter) range
    let l:saved_reg = @"
    execute "normal! vgvy"

    let l:pattern = escape(@", "\\/.*'$^~[]")
    let l:pattern = substitute(l:pattern, "\n$", "", "")

    if a:direction == 'gv'
        call CmdLine("Ack '" . l:pattern . "' " )
    elseif a:direction == 'replace'
        call CmdLine("%s" . '/'. l:pattern . '/')
    endif

    let @/ = l:pattern
    let @" = l:saved_reg
endfunction
